import React, { useState } from 'react';
import { 
  Box, 
  Typography, 
  Paper,
  Button,
  IconButton,
  Stack,
  TextField,
  CircularProgress,
  Alert
} from '@mui/material';
import { ArrowBack as ArrowBackIcon } from '@mui/icons-material';
import { useNavigate } from 'react-router-dom';
import { fetch } from '@tauri-apps/plugin-http';

const HttpCasePage = () => {
  const navigate = useNavigate();
  const [url, setUrl] = useState('https://api.github.com/users/tauri-apps');
  const [loading, setLoading] = useState(false);
  const [response, setResponse] = useState(null);
  const [error, setError] = useState(null);

  const handleFetch = async () => {
    try {
      setLoading(true);
      setError(null);
      const response = await fetch(url, {
        method: 'GET',
        headers: {
          'Accept': 'application/json'
        }
      });
      
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      
      const data = await response.json();
      setResponse(data);
    } catch (err) {
      setError(err.toString());
    } finally {
      setLoading(false);
    }
  };

  return (
    <Box sx={{ p: 3 }}>
      <Stack direction="row" alignItems="center" spacing={2} sx={{ mb: 3 }}>
        <IconButton 
          onClick={() => navigate('/')}
          sx={{ color: 'text.primary' }}
        >
          <ArrowBackIcon />
        </IconButton>
        <Typography variant="h4" component="h1" sx={{ userSelect: 'none' }}>
          HTTP 请求示例
        </Typography>
      </Stack>

      <Paper sx={{ p: 3, mb: 3 }}>
        <Typography variant="body1" paragraph>
          本示例展示如何使用 Tauri HTTP Plugin 发送网络请求。默认请求 GitHub API 获取 Tauri 组织信息。
        </Typography>
        
        <TextField
          fullWidth
          label="请求 URL"
          value={url}
          onChange={(e) => setUrl(e.target.value)}
          sx={{ mb: 2 }}
        />

        <Button 
          variant="contained" 
          onClick={handleFetch}
          disabled={loading}
          sx={{ mb: 2 }}
        >
          {loading ? <CircularProgress size={24} /> : '发送请求'}
        </Button>

        {error && (
          <Alert severity="error" sx={{ mb: 2 }}>
            {error}
          </Alert>
        )}

        {response && (
          <Paper 
            variant="outlined" 
            sx={{ 
              p: 2,
              maxHeight: 400,
              overflow: 'auto',
              '& pre': {
                margin: 0,
                whiteSpace: 'pre-wrap',
                wordWrap: 'break-word'
              }
            }}
          >
            <pre>{JSON.stringify(response, null, 2)}</pre>
          </Paper>
        )}
      </Paper>
    </Box>
  );
};

export default HttpCasePage; 